package com.shuaitao.newsystem.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shuaitao.newsystem.bean.Comments;
import com.shuaitao.newsystem.bean.News;
import com.shuaitao.newsystem.bean.Topic;
import com.shuaitao.newsystem.service.CommentsService;
import com.shuaitao.newsystem.service.NewsService;
import com.shuaitao.newsystem.service.TopicService;
import com.shuaitao.newsystem.utils.R;
import com.shuaitao.newsystem.vo.GroupNews;
import com.sun.istack.internal.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotBlank;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Validated
@Controller
@RequestMapping("/news")
public class NewsController {
    @Autowired
    private NewsService newsService;
    @Autowired
    private CommentsService commentsService;
    @Autowired
    private TopicService topicService;


    @RequestMapping("/getAllNews")
    public String getAllNews(HttpSession session, @RequestParam("pageNum") Integer pageNum,
                             @RequestParam("tid") Integer tid,
                             @RequestParam("keywords") String keywords) {
        IPage page =
                newsService.getNewPage(pageNum,tid,keywords);
        session.setAttribute("page", page);
        List<News> records = page.getRecords();
        session.setAttribute("news",records);
        long pages = page.getPages();
        session.setAttribute("pages",pages);
        return "main";
    }
    @RequestMapping("/getAdminAllNews")
    public String getAdminAllNews(HttpSession session, @RequestParam("pageNum") Integer pageNum,
                             @RequestParam("tid") Integer tid,
                             @RequestParam("keywords") String keywords) {
        IPage page =
                newsService.getNewPage(pageNum,tid,keywords);
        session.setAttribute("page", page);
        List<News> records = page.getRecords();
        session.setAttribute("news",records);
        long pages = page.getPages();
        session.setAttribute("pages",pages);
        return "/newspages/adminNews";
    }
    @RequestMapping("/toEdit")
    public String toEdit(@RequestParam("nid") Integer nid,HttpSession session) {
        News byId = newsService.getById(nid);
        session.setAttribute("detailNews",byId);
//        Page detailComments = commentsService.getDetailComments(nid, 1);
//        session.setAttribute("commentsPage",detailComments);
        List<Topic> list = topicService.list();
        session.setAttribute("topic",list);
        return "/newspages/news_modify";
    }

    @RequestMapping("/getGroupNews")
    public void getGroupNews(HttpSession session) {
        List<GroupNews> groupNews = newsService.getGroupNews();
        session.setAttribute("groupNews",groupNews);
    }

    @RequestMapping("/getDetailNews")
    public String getDetailNews(@RequestParam("nid") Integer nid,HttpSession session){
        News news = newsService.getById(nid);
//        List<Comments> detailComments = commentsService.getDetailComments(nid, pageNum, pageSize);
        session.setAttribute("detailNews",news);
//        session.setAttribute("comments",detailComments);
        return "/newspages/news_read";
    }

    @RequestMapping("/getTopicNews/{tid}")
    public String getTopicNews(@PathVariable Integer tid,HttpSession session) {
        List<News> list = newsService.getByTid(tid);
//        session.removeAttribute("news");
        session.setAttribute("news",list);
        return "index";
    }

    @RequestMapping("/delNews")
    @ResponseBody
    public R delNews(@RequestParam("nid") Integer nid){
        R r = newsService.delNews(nid);
        return r;
    }
    @RequestMapping("updateNews")
    @ResponseBody
    public R updateNews(@NotBlank @RequestParam("nauthor") String nauthor,
                     @RequestParam(value = "nsummary",required = false) String nsummary,
                     @NotBlank @RequestParam("ncontent") String ncontent,
                     @NotBlank @RequestParam("ntitle") String ntitle,
                     @RequestParam("tid") Integer tid,
                     @RequestParam("nid") Integer nid,
                     @RequestParam(value = "file",required = false) MultipartFile image) {
        News news = new News();
        news.setNauthor(nauthor);
        news.setNtid(tid);
        news.setNcontent(ncontent);
        if (nsummary != null) {
            news.setNsummary(nsummary);
        }else {
            news.setNsummary("暂无");
        }
        news.setNtitle(ntitle);
        news.setNid(nid);
        news.setNmodifydate(new Date());
        String filePath = "D:/All-of-my-project/newSystem/src/main/webapps/static/images/";
        //判断文件夹是否存在,不存在则创建
        File file=new File(filePath);

        if(!file.exists()){
            file.mkdirs();
        }
        String originalFileName = image.getOriginalFilename();//获取原始图片的扩展名
        if (originalFileName != null && originalFileName != "") {
            String newFileName = UUID.randomUUID()+originalFileName;
            String newFilePath=filePath+newFileName; //新文件的路径
            String path = newFilePath.replace("D:/All-of-my-project/newSystem/src/main/webapps/", "");
            news.setNpicpath(path);
            try {
                image.transferTo(new File(newFilePath));  //将传来的文件写入新建的文件
            }catch (IllegalStateException e ) {
                //处理异常
            }catch(IOException e1){
                //处理异常
            }
        }

        boolean save = newsService.updateById(news);
        if (save) {
            return R.ok();
        }
        return R.error(102,"添加失败！！1");
    }
    @RequestMapping("saveNews")
    @ResponseBody
    public R saveNews(@NotBlank @RequestParam("nauthor") String nauthor,
                     @RequestParam(value = "nsummary",required = false) String nsummary,
                     @NotBlank @RequestParam("ncontent") String ncontent,
                     @NotBlank @RequestParam("ntitle") String ntitle,
                     @RequestParam("tid") Integer tid,
                     @RequestParam(value = "file",required = false) MultipartFile image) {
        News news = new News();
        news.setNauthor(nauthor);
        news.setNtid(tid);
        news.setNcontent(ncontent);
        if (nsummary != null) {
            news.setNsummary(nsummary);
        }else {
            news.setNsummary("暂无");
        }
        news.setNtitle(ntitle);
        news.setNcreatedate(new Date());
        news.setNmodifydate(new Date());
        String filePath = "D:/All-of-my-project/newSystem/src/main/webapps/static/images/";
        //判断文件夹是否存在,不存在则创建
        File file=new File(filePath);

        if(!file.exists()){
            file.mkdirs();
        }
        String originalFileName = image.getOriginalFilename();//获取原始图片的扩展名
        if (originalFileName != null && originalFileName != "") {
            String newFileName = UUID.randomUUID()+originalFileName;
            String newFilePath=filePath+newFileName; //新文件的路径
            String path = newFilePath.replace("D:/All-of-my-project/newSystem/src/main/webapps/", "");
            news.setNpicpath(path);
            try {
                image.transferTo(new File(newFilePath));  //将传来的文件写入新建的文件
            }catch (IllegalStateException e ) {
                //处理异常
            }catch(IOException e1){
                //处理异常
            }
        }


        boolean save = newsService.save(news);
        if (save) {
            return R.ok();
        }
        return R.error(102,"添加失败！！1");
    }

    @RequestMapping("editNews")
    public R editNews(@RequestBody News news) {
        boolean save = newsService.updateById(news);
        if (save) {
            return R.ok();
        }
        return R.error(103,"修改失败！！1");
    }

    @RequestMapping("toAddNews")
    public String toAddNews(HttpSession session) {
        List<Topic> list = topicService.list();
        session.setAttribute("topic",list);
        return "newspages/news_add";
    }
}
